using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using XiheNet;

namespace Com.Core.Module.Filters;

/// <summary>
/// 统一错误处理过滤器，处理模型验证错误和系统异常
/// </summary>
public class UnifiedErrorFilter : IActionFilter, IExceptionFilter
{
    private readonly ILogger<UnifiedErrorFilter> _logger;

    public UnifiedErrorFilter(ILogger<UnifiedErrorFilter> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 处理模型验证错误
    /// </summary>
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // 检查模型验证状态
        if (!context.ModelState.IsValid)
        {
            // 获取第一个验证错误
            var firstError = context.ModelState
                .Where(ms => ms.Value?.Errors.Any() ?? false)
                .Select(ms => new {
                    Field = ms.Key,
                    Error = ms.Value?.Errors.First().ErrorMessage
                })
                .FirstOrDefault();

            // 创建统一格式的错误响应
            var response = CreateErrorResponse("2100", firstError?.Error ?? "数据验证失败");
            
            // 设置响应结果，强制返回200状态码
            context.Result = new ObjectResult(response) { StatusCode = StatusCodes.Status200OK };
        }
    }

    /// <summary>
    /// Action执行后不需要处理
    /// </summary>
    public void OnActionExecuted(ActionExecutedContext context)
    {
        // 不需要在Action执行后做任何处理
    }

    /// <summary>
    /// 处理系统异常
    /// </summary>
    public void OnException(ExceptionContext context)
    {
        // 创建响应对象
        var response = new XResponse<object>();
        
        // 处理已知的自定义异常
        if (context.Exception is XException xException)
        {
            _logger.LogError(xException, "业务异常: {Code} - {Message}", xException.Code, xException.Message);
            
            response.RespHead = new XRespHead
            {
                Code = xException.Code,
                Message = xException.Message
            };
        }
        else
        {
            // 处理未知异常
            _logger.LogError(context.Exception, "未处理的系统异常");
            
            response.RespHead = new XRespHead
            {
                Code = "1000",
                Message = "接口错误"
            };
        }
        
        // 设置响应结果，保持HTTP状态码为200
        context.Result = new ObjectResult(response) { StatusCode = StatusCodes.Status200OK };
        context.ExceptionHandled = true;
    }

    /// <summary>
    /// 创建错误响应的辅助方法
    /// </summary>
    private static XResponse<object> CreateErrorResponse(string code, string message)
    {
        var response = new XResponse<object>();
        response.RespHead.Code = code;
        response.RespHead.Message = message;
        return response;
    }
}
